//
//  PhoneBookViewController.m
//  HonlivApp
//
//  Created by admin on 2017/6/23.
//  Copyright © 2017年 honliv. All rights reserved.
//

#import "PhoneBookViewController.h"
#import "UIBarButtonItem+Extension.h"

@interface PhoneBookViewController ()

@property (nonatomic,assign) NSInteger backFlag;

@end

@implementation PhoneBookViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"通讯录";
    self.navigationItem.leftBarButtonItems = nil;

}
-(void)getRequestURL{
    self.user = User.currentUser;
    [self loadRequestURL:^(GetURL handler) {
        self.viewModel = [[DetailViewModel alloc] init];
        NSDictionary *gidDic = @{@"user_name":self.user.username,@"user_id":self.user.userId,@"SqlNo":@"11"};
        [self.viewModel getGidWithDic:gidDic Success:^(NSString *gid) {
            NSString *requestURL = [NSString stringWithFormat:@"%@Gid=%@",detail_url,gid];
            handler(requestURL);
        }];
    }];
}
-(void)viewDidAppear:(BOOL)animated{
    _backFlag = 0;
    self.webView.frame = CGRectMake(0, 0, kScreenW, kScreenH-64);
    [SVProgressHUD show];
}

-(void)viewWillDisappear:(BOOL)animated{
    _backFlag = 0;
    [self hideBackButtonItem];
}

//重写父类方法 修改关闭按钮作用
-(void)closeWebView{
    [self.webView goToBackForwardListItem:self.webView.backForwardList.backList.firstObject];
}
//在这里判断返回
-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    _backFlag = _backFlag < 2 ? ++_backFlag : 6;
    if (_backFlag == 6) {
        [self createBackBtn];
    }
    if (navigationAction.navigationType == WKNavigationTypeBackForward){
        if (![self.webView canGoBack]) {
            _backFlag = 2;
            [self hideBackButtonItem];
        }
    }

    //拨打电话
    NSURL *URL = navigationAction.request.URL;
    NSString *scheme = [URL scheme];
    if ([scheme isEqualToString:@"tel"]) {
        NSString *resourceSpecifier = [URL resourceSpecifier];
        NSString *callPhone = [NSString stringWithFormat:@"tel://%@", resourceSpecifier];
        /// 防止iOS 10及其之后，拨打电话系统弹出框延迟出现
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
        });
    }else if ([scheme isEqualToString:@"sms"]) {
        NSString *resourceSpecifier = [URL resourceSpecifier];
        NSString *sendMessage = [NSString stringWithFormat:@"sms://%@", resourceSpecifier];
        /// 防止iOS 10及其之后，拨打电话系统弹出框延迟出现
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:sendMessage]];
        });
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
}

//取消返回按钮
-(void)hideBackButtonItem{
    self.navigationItem.leftBarButtonItems = nil;
}



@end
